package com.mycontract.suitepro.utils.analytics.util

import android.app.Application
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.mycontract.suitepro.utils.analytics.bean.ParamGoogleInstall
import com.mycontract.suitepro.utils.analytics.http.HttpHelper
import com.google.gson.Gson
import com.mycontract.suitepro.ProjectApplication
import com.mycontract.suitepro.contract.ContractParamsFromReferrer
import com.mycontract.suitepro.network.ApiUrl
import com.mycontract.suitepro.utils.AppConfigUtil

object GoogleInstallUtil {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var mInstallReferrer: String = ""

    /** 句柄 */
    private var mInstallReferrerClient: InstallReferrerClient =
        InstallReferrerClient.newBuilder(ProjectApplication.instance).build()

    /**
     * 初始化google install referref模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) {
            val pathList =
                AppConfigUtil.getContractSuiteValidContractSuiteCountrysContractSuitePaths()
            saveS2sInfo(pathList)

            // 初始化模块
            ContractParamsFromReferrer.initSourceData(getInstallReferrer())
        }
    }

    /**
     * 初始化google install referref模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String) -> Unit) {
        try {
            if (mInstallReferrer.isBlank()) {
                mInstallReferrerClient.startConnection(object :
                    InstallReferrerStateListener {
                    override fun onInstallReferrerSetupFinished(responseCode: Int) {
                        when (responseCode) {
                            InstallReferrerClient.InstallReferrerResponse.OK -> {
                                try {
                                    val response = mInstallReferrerClient.installReferrer
                                    mInstallReferrer = response?.installReferrer ?: ""
                                    mInstallReferrerClient.endConnection()

                                    // 有数据
                                    //mInstallReferrer = "orderId=value1&mobile=9168888889&product=LOANSALAD&sourceType=app&scheme=toolshake&host=doshake"
//                                    mInstallReferrer = "427D77AE088BF28B5D2734962C1CE28F"

                                    // 输出 install referrer
                                    println("install referrer: $mInstallReferrer")

                                    //回调通知
                                    success.invoke(getInstallReferrer())

                                } catch (e: Exception) {
                                    e.printStackTrace()
                                    mInstallReferrerClient.endConnection()
                                }
                            }
                            InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {

                                println("FEATURE_NOT_SUPPORTED")
                                mInstallReferrerClient.endConnection()
                            }
                            InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {

                                println("SERVICE_UNAVAILABLE")
                                mInstallReferrerClient.endConnection()
                            }
                        }
                    }

                    override fun onInstallReferrerServiceDisconnected() {
                    }
                })
            } else {
                //回调通知
                success.invoke(getInstallReferrer())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取Install Referrer
     */
    fun getInstallReferrer(): String {
        return mInstallReferrer
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo(targetUrlList: List<String>) {
//        val params =
//            ParamGoogleInstall(
//                channelCode = getInstallReferrer(),
//                subChannelCode = getInstallReferrer()
//            )
//        val body = Gson().toJson(params).trim()
//        println("====== $targetUrlList")
//
//        //传多国时，里触发多次
//        val apiPath = ApiUrl.CONTRACTSUITE_PATH_GOOGLE_INSTALL
//        targetUrlList.forEach { host ->
//            val pathFormat =
//                if (host.endsWith(apiPath)) host else (host + apiPath)
//            HttpHelper.postData(pathFormat, body)
//        }
    }
}